package com.adobe.coreUI.controls
{
	import com.adobe.coreUI.controls.whiteboardClasses.*;
	import com.adobe.coreUI.controls.whiteboardClasses.shapes.*;
	import com.adobe.coreUI.events.OutPutCmd;
	import com.adobe.coreUI.events.WBCanvasEvent;
	import com.adobe.coreUI.events.WBModelEvent;
	import com.adobe.serialization.json.*;
	import com.adobe.util.ObjectUtil;
	
	import flash.geom.Point;
	
	import mx.core.UIComponent;
	import mx.events.FlexEvent;
	import mx.controls.Alert;

	
	/**
	 * Dispatched when the property tool bar is added.
	 */
	[Event(name="propertiesToolbarAdd", type="com.adobe.events.WBCanvasEvent")]
	/**
	 * Dispatched when the property tool bar is removed.
	 */
	[Event(name="propertiesToolbarRemove", type="com.adobe.events.WBCanvasEvent")]
	/**
	 * Dispatched when one is finished drawing a shape on the  canvas.
	 */	
	[Event(name="endDrawingShape", type="com.adobe.events.WBCanvasEvent")]

	/**
	 * This is a standalone whiteboard component. The SharedWhiteBoard component extends this component.
	 * This has API's for setting the shapes tool bar , properties tool bar, zoom level, selection.
	 * It has a white board model that does bookkeeping of all the shapes.
	 */
	 public class WhiteBoard extends UIComponent
	{
		/**
		 * @private
		 */
		protected var _toolBar:WBShapesToolBar;
		/**
		 * @private
		 */
		protected var _propsBar:UIComponent;
		/**
		 * @private
		 */
		protected var _canvas:WBCanvas;
		/**
		 * @private
		 */
		protected var _model:WBModel;
		/**
		 * @private
		 */
		protected var _zoomLevel:Number = 1;
		/**
		 * @private
		 */
		protected var _invZoom:Boolean = false;
		/**
		 * @private
		 */
		protected var _toolDP:Object;
		/**
		 * @private
		 */
		protected var _propsPt:Point;
		/**
		 * @private
		 */
		protected var _allowSave:Boolean = false;
		/**
		 * @private
		 */
		protected var _selectionContainer:UIComponent;
		
		/**
		 * Returns if the properties tool bar is popped up.
		 */
		public var popupPropertiesToolBar:Boolean = true;
		/**
		 * Returns if the shapes tool bar is popped up.
		 */
		public var popupShapesToolBar:Boolean = true;
		
		public var Debug :Boolean=true;
		private var i_obj_json:int =0;
		//protected var _arrshape:WBArrowShape;
		
		public function WhiteBoard(toobar:WBShapesToolBar=null){
			super();
			_toolBar =toobar;
			
		}
		
		/**
		 * Returns the model
		 */
		public function get model():WBModel
		{
			return _model;
		}
		
		/**
		 * The shapes tool Bar
		 */
		public function get shapesToolBar():UIComponent
		{
				//	}
		   
			return _toolBar;
		}
		
		public function wbControl(iCon:String):void{
			_toolBar.wbControl(iCon);
		}
		
		public function setCanvasWH(width:int,height:int):void{
			_canvas.width = width;
			_canvas.height = height;
		}
		
		public function setCanvasScale(scale:Number):void{
			_canvas.scaleX = scale;
			_canvas.scaleY = scale;
		}
		
		public function removeAllObject():void
		{
			_canvas.removeAllChildren();
//			while(this.numChildren>0)  {
//				this.removeChildAt(0);
//			}
		}
			
		//}
		/**
		 * @private
		 */
		public function set shapesToolBar(p_toolBar:UIComponent):void
		{
			print_debug("shapesToolBar","starting...");
			_toolBar = WBShapesToolBar(p_toolBar);
			invalidateProperties();
		}

		/**
		 * The current properties tool bar
		 */
		public function get currentPropertiesToolBar():IWBPropertiesToolBar
		{
			return _canvas.currentPropertiesToolBar;
		}

		/**
		 * @private
		 */
		public function set zoomLevel(p_level:Number):void
		{
			if (p_level!=_zoomLevel) {
				_zoomLevel = p_level;
				_invZoom = true;
				invalidateDisplayList();
			}
		}
		
		/**
		 * Returns the zoom level
		 */
		public function get zoomLevel():Number
		{
			return _zoomLevel;
		}

		/**
		 * @private
		 */
		public function set allowSave(p_allow:Boolean):void
		{
			_allowSave = p_allow;
		}
		
		/**
		 * Returns true if saving is allowed
		 */
		public function get allowSave():Boolean
		{
			return _allowSave;
		}

		/**
		 * Hides the selection container
		 */
		public function hideSelection():void
		{
			if (_selectionContainer) {
				_selectionContainer.visible = false;
			}
		}
		
		/**
		 * Shows the selection
		 */
		public function showSelection():void
		{
			if (_selectionContainer) {
				_selectionContainer.visible = true;
			}
		}
		/**
		 * @private
		 */
		override protected function createChildren():void
		{
			print_debug("createChildren","start...");			
			_canvas = new WBCanvas();
			addChild(_canvas);
			_selectionContainer = new UIComponent();
			addChild(_selectionContainer);
			_canvas.selectionHandlesContainer = _selectionContainer;
			_canvas.popupPropertiesToolBar = false;
			_canvas.addEventListener(WBCanvasEvent.PROPERTIES_TOOLBAR_ADD, addProps);
			_canvas.addEventListener(WBCanvasEvent.PROPERTIES_TOOLBAR_REMOVE, removeProps);
			_canvas.addEventListener(WBCanvasEvent.END_DRAWING_SHAPE, endDrawingShape);
			_canvas.addEventListener(FlexEvent.UPDATE_COMPLETE,traceScrollBar);
			this.addEventListener(FlexEvent.UPDATE_COMPLETE,traceScrollBar);
			_canvas.styleName = this;
			//*
			if(_toolBar ==null){
				_toolBar = new WBShapesToolBar();///初始化 1
			}
			_toolBar.wbCanvas = _canvas;
			///_toolBar.setStyle("position","absolute");
			_toolBar.allowSave = _allowSave;
			//*/
		}
		
		protected function traceScrollBar(event:FlexEvent):void{
			print_debug("traceScrollBar","start...");	
		}
		
		/**
		 * @private
		 */
		protected function endDrawingShape(p_evt:WBCanvasEvent):void
		{			
			dispatchEvent(p_evt);
		}
		/**
		 * @private
		 */
		protected function addProps(p_evt:WBCanvasEvent):void
		{
			print_debug("addProps","start...");	
			if (popupPropertiesToolBar) {
				_propsBar = UIComponent(_canvas.currentPropertiesToolBar);
				if(_toolBar){
					_toolBar.tmpPropsBar(_propsBar);
				}
				this.parent.parent.addChild(_propsBar);////////////
				//addChild(_propsBar);
				_propsBar.validateNow();
				_propsBar.setActualSize(_propsBar.measuredWidth, 25);
				
                _propsBar.height = 20;
                var _toolBarX:int = 450;
                var _toolBarY:int = -10;
             
               var str:String =_propsBar.toString();
               var num:int =str.indexOf('.');
               var _Propsbar:String =str.substring(num + 1, num + 14);
               
               trace(str)
               trace(num)
               trace(_Propsbar);
				if (_propsPt) {
                    if(_Propsbar=="WBTextToolBar")
                    {
                    _propsBar.move(_toolBarX+_toolBar.width+32,_toolBarY - 7)
                    }else
                    {
                    _propsBar.move(_toolBarX+_toolBar.width+32,_toolBarY + 14);
                    }
                     
			 } else {
                    if(_Propsbar=="WBTextToolBar")
                    {
                    _propsBar.move(_toolBarX+_toolBar.width+32,_toolBarY - 7)
                    }else
                    {
                    _propsBar.move(_toolBarX+_toolBar.width+32,_toolBarY + 14);
                    }
					
				}
				///+_toolBar.height+50
				//Alert.show("x:" + _propsBar.x + " |y:" +_propsBar.y +" |_propsPt:" +_propsPt);///
			}
			dispatchEvent(p_evt);
		}
		
		/**
		 * @private
		 */
		protected function removeProps(p_evt:WBCanvasEvent):void
		{
			print_debug("removeProps","start...");	
			if (popupPropertiesToolBar) {
				_propsPt = new Point(_propsBar.x, _propsBar.y);
				if(_propsBar && this.parent.parent.contains(_propsBar)){
					this.parent.parent.removeChild(_propsBar);
					//_propsBar =null;
				}
				//removeChild(_propsBar);
			}
			dispatchEvent(p_evt);
		}

		/**
		 * @private
		 * 提交组件属性的任何变化，或者确认属性的变化是同时发生的，或者确保属性值按一定顺序设置的。 
		 */
		override protected function commitProperties():void
		{
			print_debug("commitProperties","start...");	
			if (!_model) {
				_model = new WBModel();
				_canvas.model = _model;
			}
			var mymodel :WBModel=_model;
			//lixc 2009-07-16	ShapeChange 白板上sharpe有变化时调用
			mymodel.addEventListener( "shapeAdd" , ShapeChange );		
			mymodel.addEventListener( "shapePositionSizeRotationChange" , ShapeChange );
			mymodel.addEventListener( "shapePropertiesChange" , ShapeChange );
			mymodel.addEventListener( "shapeRemove" , ShapeChange );
			if (popupShapesToolBar && !contains(_toolBar)) {
				///addChild(_toolBar);
				///_toolBar.x = _toolBar.y = 25;///初始化 2
//				_toolBar.setActualSize(200, 500)
			} else if (contains(_toolBar)) {
				///removeChild(_toolBar);
			}
		}
		private function ShapeChange(event:WBModelEvent):void
		{				
				print_debug("ShapeChange","start...");	
			 	var mymodel:WBModel = _model;		
				var sharpe :WBShapeDescriptor = mymodel.getShapeDescriptor( event.shapeID );
				var sharpestr :String=""; 
				if (event.isLocalChange==false) return;
				if (sharpe) {
					//lixc 初始化输出xml
					var sharpexml:XML =Initializationxml(event.type,sharpe);					
					print_debug(sharpexml.toString());
					var evt:OutPutCmd = new OutPutCmd(OutPutCmd.SHAPE_OUT);
					evt.xmlobject = sharpexml.toString();
					
					dispatchEvent(evt);
					
					}
				if (event.type==WBModelEvent.SHAPE_REMOVE){
					var evt2:OutPutCmd = new OutPutCmd(OutPutCmd.SHAPE_OUT);
					evt2.xmlobject = "<sharpe> <event_type>shapeRemove</event_type> <shapeID>"+event.shapeID+"</shapeID></sharpe>";
					dispatchEvent(evt2);					
				}
		}
	
		  
		/**
		 * @private
		 * 根据组件的属性和样式，设置组件子元素的大小和位置，绘制组件使用的皮肤或者图形元素。组件父容器的大小决定了组件的大小。
		 */
		override protected function updateDisplayList(p_width:Number, p_height:Number):void
		{
			print_debug("updateDisplayList","start...");	
			_selectionContainer.setActualSize(p_width, p_height);
			///_toolBar.setActualSize(_toolBar.measuredWidth, _toolBar.measuredHeight);///初始化 3 点击2
			///_toolBar.x = Math.min(_toolBar.x, width-_toolBar.width);
			///_toolBar.y = Math.min(_toolBar.y, height-50);
			
			//print_debug("y:"+y + " this.y:" + this.y + " this.parent.y:" + this.parent.y + " _toolBar.y:" + _toolBar.y + " this.parent.parent.y:" + this.parent.parent.y);
			//_toolBar.x = this.parent.x;
			//_toolBar.y = this.parent.y;
			if (_invZoom) {
				_invZoom = false;
				_canvas.scaleX = _canvas.scaleY = _zoomLevel;
			}               
			_canvas.setActualSize(p_width,p_height);
		}
		/*
		override protected function scrollChildren():void {
			super.scrollChildren();
		}
		*/
		/**
		 * @private
		 * 设置组件的默认大小及默认的最小尺寸。 
		 */
		override protected function measure():void
		{
			print_debug("measure","start...");
			super.measure();
			minWidth = _toolBar.measuredWidth + 100 ;
			minHeight = _toolBar.measuredHeight ;
		}
		
		/**
		 * 函数名：Initializationxml
		 * 功能描述：用于将sharpe到描述对象转换为xml格式字符串。
		 * 输入参数：eventtype：事件类型(如sharpeAdd)
		 * 		   sharpe:描述对象
		 * 输出：xml对象
		 * 创建人：lixc
		 * 日期：2009-07-16 
		 */
		protected function Initializationxml(eventtype:String,sharpe:WBShapeDescriptor):XML
		{
			print_debug("Initializationxml","start...");
			var objson:String= ObjectUtil.obj_json_encoder1(sharpe);
			var sharpexml:XML=<sharpe><event_type>{eventtype}</event_type><objjson>{objson}</objjson></sharpe>
			return sharpexml;
		}
		/**
		 * 函数名：setsharp
		 * 功能描述：将xml格式字符串转换为sharpe对象并画在白板上。
		 * 输入参数：sharpexmlrec：xml对象
		 * 输出：空
		 * 创建人：lixc
		 * 日期：2009-07-16 
		 */
		public function setsharp(sharpexmlrec:XML,textxml:String):void
		{
			print_debug("setsharp","start...");
			if (sharpexmlrec.event_type=="shapeAdd"){
				//lixc 当xml类型为shapeAdd-添加
								//setsharpeadd(sharpexmlrec);
								
				setsharpeaddNew(sharpexmlrec.objjson,textxml);
			}
			else if (sharpexmlrec.event_type=="shapeRemove"){
				//lixc 当xml类型为shapeRemove-删除
				setsharperemove(sharpexmlrec);
			}else if (sharpexmlrec.event_type=="shapePositionSizeRotationChange" ) {
				//lixc 当xml类型为other-修改
				shapePositionSizeRotationChange(sharpexmlrec.objjson);
				
			}else if (sharpexmlrec.event_type=="shapePropertiesChange" ) {
				//lixc 当xml类型为other-修改
				shapePropertiesChange(sharpexmlrec.objjson,textxml);				
			}else{
				print_debug("ERROR WRONG EVENT_TYPE");
				
			}
		}
		
		protected function shapePropertiesChange(obj_json:String,textxml:String):void
		{
			print_debug("shapePropertiesChange","start...");
			var  tmp:String= obj_json;

			if (textxml!=""){
			  tmp	=tmp.replace("mmmmmmmmmmm",textxml);
			}

			print_debug(tmp);
			var obj:Object = ObjectUtil.obj_json_decoder1(tmp);			

			var shapeid:String = obj.shapeID;
			var ApropertyData: Object=new Object();
			ApropertyData=obj.propertyData;						
			
			_model.changeShapeProperties(shapeid,ApropertyData,false);
		}
		
		
		protected function shapePositionSizeRotationChange(obj_json:String):void
		{
			print_debug("shapePositionSizeRotationChange","start...");
			var obj:Object = ObjectUtil.obj_json_decoder1(obj_json);
			
			var x:Number  = obj.x;
			var y:Number  = obj.y;
			var w:Number  = obj.width;
			var h:Number  = obj.height;
			var shapeid:String = obj.shapeID;
			var r:Number = obj.rotation;
			
			_model.moveSizeRotateShape(shapeid,x,y,w,h,r,false);
		}
		
		protected function setsharpeaddNew(obj_json:String,textxml:String):void
		{
			print_debug("setsharpeaddNew","start...");
			var  tmp:String= obj_json;

			if (textxml!=""){
			  tmp	=tmp.replace("mmmmmmmmmmm",textxml);
			}

		//	Alert.show(tmp,"setsharpeaddNew");
			print_debug(tmp);
			var obj:Object = ObjectUtil.obj_json_decoder1(tmp);
			
			var shapearrowDesc:WBShapeDescriptor =   new WBShapeDescriptor();
			shapearrowDesc.factoryID = obj.factoryID;
			shapearrowDesc.height = obj.height;
			shapearrowDesc.rotation =obj.rotation; 
			shapearrowDesc.width = obj.width;
			shapearrowDesc.x = obj.x;
			shapearrowDesc.y = obj.y;
			shapearrowDesc.shapeID = obj.shapeID;
			
		//	if (shapearrowDesc.factoryID="com.adobe.coreUI.controls.whiteboardClasses.shapes::WBArrowShapeFactory")
			{
				var ApropertyData: Object=new Object();
				ApropertyData=obj.propertyData;
				var AdefinitionData: Object=new Object();
				AdefinitionData=obj.definitionData;
				shapearrowDesc.definitionData = AdefinitionData;
				shapearrowDesc.propertyData = ApropertyData;				
			} 
			
			
			//shapearrowDescvar shapearrowDesc:WBShapeDescriptor =  WBShapeDescriptor(obj);
		//	obj.x +=20;
			//obj.y +=20;
			//obj.shapeID = "mmmmm";
			_model.addShape(shapearrowDesc,false);	
		}
		/**
		 * 函数名：setsharpeadd
		 * 功能描述：根据xml格式字符串新画sharpe对象在白板上。
		 * 输入参数：sharpexmlrec：xml对象
		 * 输出：空
		 * 创建人：lixc
		 * 日期：2009-07-16 
		 */
	
		/**
		 * 函数名：setsharperemove
		 * 功能描述：根据xml格式字符串删除原有的sharpe对象。
		 * 输入参数：sharpexmlrec：xml对象
		 * 输出：空
		 * 创建人：lixc
		 * 日期：2009-07-16 
		 */
		protected function setsharperemove(sharpexmlrec:XML):void
		{
			print_debug("--setsharperemove--"+sharpexmlrec.toString()+sharpexmlrec.shapeID)
			_model.removeShape(sharpexmlrec.shapeID,false);
		}
	
		private function print_debug(func:String,info:String=""):void{
			trace("WhiteBoad.as || "+func + " | " + info );
			//Alert.show(""+func + " | " + info );
		}
	}
}